package com.telecomyt.jwportal.activity.camera;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.telecomyt.jwportal.R;
import com.telecomyt.jwportal.activity.camera.bean.CameraBean;
import com.telecomyt.jwportal.activity.conference.ConferenceActivity;
import com.telecomyt.jwportal.base.BaseActivity;
import com.telecomyt.jwportal.utils.GlideUtils;

import java.io.IOException;
import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 通话页面
 */
public class CameraActivity extends BaseActivity<CameraPresenter> implements CameraContract.View, SurfaceHolder.Callback {
    public SurfaceHolder mHolder;
    @BindView(R.id.mSurfaceView)
    SurfaceView mSurfaceView;
    @BindView(R.id.mImageView)
    ImageView mImageView;
    @BindView(R.id.mImageHead)
    ImageView mImageHead;
    @BindView(R.id.mTvStop)
    TextView mTvStop;
    private Camera mCamera;
    private Camera.Parameters mParameters;
    private boolean isFinish = true;
    private boolean mIsClose = false;

    public static void start(Context context) {
        Intent intent = new Intent(context, CameraActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_camera;
    }


    @Override
    protected void initView() {
        //加载头像
        GlideUtils.load(this, "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=15979962503" +
                "14&di=9efae55233ac66124b5b3baa0fd14e70&imgtype=0&src=http%3A%2F%2Fb-ssl" +
                ".duitang.com%2Fuploads%2Fitem%2F201412%2F28%2F20141228171331_L5T2n.jpeg", mImageHead);
//        glideRequest.load().transform(new GlideCircleTransform(this,10)).into(mImageHead);
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        CountDownTimer timer = new CountDownTimer(5000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (isFinish) {
                    mIsClose = true;
                    ConferenceActivity.start(CameraActivity.this);
                    dismissFloatingView();
                    Toast.makeText(CameraActivity.this, "5秒时间到了，跳转了", Toast.LENGTH_SHORT).show();
                }
            }
        };
        timer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isFinish = false;
    }

    /**
     * 跳转应用详情界面
     *
     * @param context
     */
    private void jumpDetailActivity(Context context) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", context.getPackageName(), null));
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        dismissFloatingView();

    }


    @Override
    protected void onPause() {
        super.onPause();
        if (!mIsClose) {
            //显示悬浮窗
            showFloatingView();
        }
    }

    /**
     * 获取数据
     */
    @Override
    protected void initData() {
        persenter.getData();

    }


    /**
     * 设置接口数据
     */
    @Override
    public void setCameraData(CameraBean cameraData) {

    }

    @Override
    protected CameraPresenter creatPresenter() {
        return new CameraPresenter(this);
    }


    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            // Open the Camera in preview mode
            mCamera = Camera.open(1);
            mCamera.setDisplayOrientation(90);
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCamera.autoFocus(new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if (success) {
                    mParameters = mCamera.getParameters();
                    mParameters.setPictureFormat(PixelFormat.JPEG); //图片输出格式
//                    mParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);//预览持续发光
                    mParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//持续对焦模式
//                    mCamera.setParameters(mParameters);
                    mCamera.startPreview();
                    mCamera.cancelAutoFocus();


                }
            }
        });
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }


    @OnClick({R.id.mImageView, R.id.mTvStop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mImageView:
                isFinish = false;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    //判断是否拥有悬浮窗权限，无则跳转悬浮窗权限授权页面
                    if (Settings.canDrawOverlays(CameraActivity.this)) {
                        showFloatingView();
                        finish();
                    } else {
                        //跳转悬浮窗权限授权页面
                        jumpDetailActivity(CameraActivity.this);
                    }
                } else {
                    showFloatingView();
                    finish();
                }
                break;
            case R.id.mTvStop:
                isFinish = false;
                mIsClose = true;
                finish();
                break;
        }
    }


    /**
     * 请求悬浮窗权限
     *
     * @param context 上下文
     */
    private void requestPermission(Context context) {
        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 23) {
        } else if (Build.VERSION.SDK_INT >= 23) {
            highVersionJump2PermissionActivity(context);
        }
    }

    /**
     * Android 6.0 版本及之后的跳转权限申请界面
     *
     * @param context 上下文
     */
    private void highVersionJump2PermissionActivity(Context context) {
        try {
            Class clazz = Settings.class;
            Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION");
            Intent intent = new Intent(field.get(null).toString());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("package:" + context.getPackageName()));
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e("TAG", Log.getStackTraceString(e));
        }
    }


}
